import { memo, useState, useEffect, useRef } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { Button, Avatar, Tag, FloatButton, message } from "antd";
import {
  LikeOutlined,
  StarOutlined,
  CommentOutlined,
  ShareAltOutlined,
  StarFilled,
  LikeFilled,
  ArrowLeftOutlined,
} from "@ant-design/icons";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Article, Comment as CommentType } from "@/types";
import {
  getRelatedArticles,
  getCurrentArticle,
  getCurrentArticleComments,
  collectCurrentArticle,
  cancelCollectCurrentArticle,
  cancelLikeCurrentArticle,
  addLikeCurrentArticle,
} from "@/services/articles";
import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";
import { CopyButton } from "@/components/CopyButton";
import { oneLight } from "react-syntax-highlighter/dist/esm/styles/prism";
import { Comment } from "@/pages/CurrentArticle/components/Comment";
import { motion, useScroll } from "motion/react"
import Loading from "@/components/Loading";
interface TocItem {
  id: string;
  level: number;
  text: string;
}

const CurrentArticle = memo(() => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { scrollYProgress } = useScroll()
  const [article, setArticle] = useState<Article | null>(null);
  const [toc, setToc] = useState<TocItem[]>([]);
  const [activeTocId, setActiveTocId] = useState<string>("");
  const contentRef = useRef<HTMLDivElement>(null);
  const [relatedArticles, setRelatedArticles] = useState<Article[]>([]);
  // 评论列表
  const [comments, setComments] = useState<CommentType[]>([]);
  const [isStar, setIsStar] = useState(false);
  const [isLike, setIsLike] = useState(false);
  const [isFlower, setIsFlower] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();

  // 记录上个路由状态
  const [fatherRouter, setFatherRouter] = useState<string>("/");
  const { state } = useLocation();
  // 评论数
  const [commentCount, setCommentCount] = useState(0);
  // pubsub 订阅评论数
  PubSub.subscribe('commentCount', (_, data: number) => {
    setCommentCount(data);
  });
  const [loading, setLoading] = useState(true);
  
  // 获取路由状态
  useEffect(() => {
    // 获取上个路由的状态
    setFatherRouter(state?.from || '/')
  }, [state])

  // 获取文章详情
  useEffect(() => {
    if (id) {
      getCurrentArticle(id).then((res) => {
        if (res) {
          setArticle(res);
          // 获取相关文章
          getRelatedArticles(res).then((res) => {
            setRelatedArticles(res);
          });
        }
      });
      // 获取评论数据
      getCurrentArticleComments(id).then((res) => {
        if (res) {
          setComments(res);

        }
      });
    }
  }, [id, navigate]);

  // 获取路由
  useEffect(() => {
    const hash = window.location.hash;
    if (hash) {
      const id = hash.split("#")[1];
      setActiveTocId(id);

      // 延迟滚动，确保DOM和目录都已加载
      setTimeout(() => {
        const element = document.getElementById(id);
        if (element) {
          const headerHeight = 80;
          const elementTop = element.offsetTop - headerHeight + 0;
          window.scrollTo({
            top: elementTop,
            behavior: 'smooth'
          });
        }
      }, 0); // 增加延迟时间，确保内容完全加载
    }
  }, [id, article?.content]);

  // 生成目录
  useEffect(() => {
    if (contentRef.current) {
      const headings = contentRef.current.querySelectorAll("h1, h2, h3");
      // 生成目录
      const tocItems: TocItem[] = Array.from(headings).map((heading, index) => {
        const id = "heading-" + index;
        heading.id = id;
        return {
          id,
          level: parseInt(heading.tagName[1]),
          text: heading.textContent || "",
        };
      });
      setToc(tocItems);
    }
  }, [article?.content]);
  // 监听标题滚动
  useEffect(() => {
    const headings = contentRef.current?.querySelectorAll("h1, h2, h3");
    if (!headings) return;
    // 获取导航栏高度
    const headerHeight = document.querySelector("#obRoot")?.clientHeight || 0;
    const observer = new IntersectionObserver((entries) => {
      const entry = entries[0];
      if (entry.isIntersecting) {
        const headingId = entry.target.id;
        if (headingId !== activeTocId) {
          setActiveTocId(headingId);
          // 更新URL hash，但不触发滚动
          const newUrl = `${window.location.pathname}#${headingId}`;
          window.history.replaceState(null, '', newUrl);
        }
      }
    }, {
      // 从导航栏下边缘开始观察，减少底部观察区域, 锁定顶部极小部分,只有一个标题
      rootMargin: `-${headerHeight}px 0px -90% 0px`,
      threshold: [0, 0.1, 0.25, 0.5, 0.75, 1],
    });

    // 观察所有标题
    headings.forEach((heading) => {
      observer.observe(heading);
    });

    return () => {
      headings.forEach((heading) => {
        observer.unobserve(heading);
      });
      observer.disconnect();
    };
  }, [article?.content, activeTocId]);
  // 模拟加载
  useEffect(() => {
    setInterval(() => {
      setLoading(false)
    }, 600)
  })

  // 目录点击处理
  const handleTocClick = (id: string) => {
    setActiveTocId(id);

    // 更新URL hash
    const newUrl = `${window.location.pathname}#${id}`;
    window.history.replaceState(null, '', newUrl);
    // 滚动到目标元素
    const element = document.getElementById(id);
    if (element) {
      const headerHeight = document.querySelector("#obRoot")?.clientHeight || 0;
      const elementTop = element.offsetTop - headerHeight - 20;
      window.scrollTo({
        top: elementTop
      });
    }
  };

  // 监听 hash 变化
  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.slice(1);
      if (hash && hash !== activeTocId) {
        setActiveTocId(hash);
        // 延迟滚动，确保DOM已更新
        setTimeout(() => {
          const element = document.getElementById(hash);
          if (element) {
            const headerHeight = document.querySelector("#obRoot")?.clientHeight || 0;
            const elementTop = element.offsetTop - headerHeight - 20;
            window.scrollTo({
              top: elementTop,
              behavior: 'smooth'
            });
          }
        }, 100);
      }
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, [activeTocId]);

  if (!article) {
    return <div>加载中...</div>;
  }

  const handleStar = async () => {
    if (!article) return;
    try {
      if (isStar) {
        await cancelCollectCurrentArticle(article.id);
        setArticle({ ...article, stars: Math.max(0, article.stars - 1) });
      } else {
        await collectCurrentArticle(article.id);
        setArticle({ ...article, stars: article.stars + 1 });
      }
      setIsStar(!isStar);

    } catch (error) {
      console.error("收藏操作失败:", error);
    }
  };

  const handleLike = async () => {
    if (!article) return;
    try {
      if (isLike) {
        await cancelLikeCurrentArticle(article.id);
        setArticle({ ...article, likes: Math.max(0, article.likes - 1) });
      } else {
        await addLikeCurrentArticle(article.id);
        setArticle({ ...article, likes: Math.max(0, article.likes + 1) });
      }
      setIsLike(!isLike);
    } catch (error) {
      console.error("点赞操作失败:", error);
    }
  };

  const handleShare = () => {
    navigator.clipboard.writeText(window.location.href);
    messageApi.success("链接已复制到剪贴板🤐")
  };

  return (
    <>
      {contextHolder}
      <Loading show={loading} />
      <motion.div
        id="scroll-indicator"
        style={{
          scaleX: scrollYProgress,
          position: "fixed",
          top: 64,
          left: 0,
          right: 0,
          height: 5,
          originX: 0,
          zIndex: 1000,
          backgroundColor: "#1677ff",
        }}
      />
      <div className="max-w-7xl mx-auto px-4 pb-8">
        {/*返回上一级 点赞 收藏 评论 分享 */}
        <div
          className="fixed left-10 transform -translate-y-1/2 z-10"
          style={{ top: "100%" }}
        >
          <FloatButton.Group shape="circle" style={{ left: "24px" }}>
            <FloatButton
              onClick={() => {
                navigate(fatherRouter);
              }}
              icon={<ArrowLeftOutlined />}
            />
            <FloatButton
              onClick={handleStar}
              badge={{ count: article.stars, color: "blue" }}
              icon={
                isStar ? (
                  <StarFilled style={{ color: "#DEA123" }} />
                ) : (
                  <StarOutlined />
                )
              }
            />
            <FloatButton
              onClick={handleLike}
              badge={{ count: article.likes, color: "blue" }}
              icon={
                isLike ? (
                  <LikeFilled style={{ color: "#1AAB29" }} />
                ) : (
                  <LikeOutlined />
                )
              }
            />
            <FloatButton
              badge={{ count: commentCount, color: "blue" }}
              icon={<CommentOutlined />}
            />
            <FloatButton icon={<ShareAltOutlined />} onClick={handleShare} />
          </FloatButton.Group>
        </div>

        {/* 文章封面区域 */}
        <div className="relative mb-10 rounded-lg overflow-hidden shadow-lg">
          <img
            src={article.cover}
            alt={article.title}
            className="w-full h-[400px] object-cover"
          />
          <div className="absolute bottom-0 left-0 right-0 p-6 bg-gradient-to-t from-black/70 to-transparent text-white">
            <h1 className="text-3xl font-bold mb-4">{article.title}</h1>
            <div className="text-sm mb-4">{article.summary}</div>
            <div className="mb-4">
              {article.tags.map((tag: string, index: number) => (
                <Tag color="blue" key={index}>
                  {tag}
                </Tag>
              ))}
            </div>
            <div className="flex items-center gap-4 mb-3">
              <Avatar src={article.author.avatar} />
              <span>{article.author.username}</span>
              <span>{new Date(article.publishTime).toLocaleDateString()}</span>
              <Button type="primary" color="purple" onClick={() => setIsFlower(!isFlower)} variant="filled">
                {isFlower ? "已关注" : "关注"}
              </Button>
            </div>
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="flex flex-col lg:flex-row gap-8">
          <div className="flex-1 min-w-0 bg-white p-4">
            {/* 文章内容 */}
            <div className="prose max-w-none mb-10">
              <div className="markdown-body" ref={contentRef}>
                <ReactMarkdown
                  remarkPlugins={[remarkGfm]}
                  components={{
                    code({ className, children, ...props }) {
                      const match = /language-(\w+)/.exec(className || "");
                      // 生成唯一id
                      const id = `code-${Math.random().toString(36).substr(2, 9)}`;
                      return match ? (
                        <div className="relative">
                          <CopyButton id={id} />
                          <SyntaxHighlighter
                            language={match[1]}
                            style={oneLight}
                            id={id}
                            className="px-1.5 py-0.5 rounded-md ::-webkit-scrollbar"
                          >
                            {String(children).replace(/\n$/, "")}
                          </SyntaxHighlighter>
                        </div>
                      ) : (
                        <code
                          className="shadow text-[#eb8619] px-1.5 py-0.5 bg-smallLightArea mx-1 dark:bg-smallDarkArea rounded-md"
                          {...props}
                        >
                          {children}
                        </code>
                      );
                    },
                    pre({ children }) {
                      return (
                        <div className="rounded-[8px] p-[1rem] m-[1rem] border-l-4 relative bg-[#fafafa] border-[#eb8619]">
                          {/* Mac 风格窗口装饰 */}
                          <div className="absolute top-3 left-3 flex gap-1.5">
                            <div className="w-3 h-3 rounded-full bg-[#FF5F56] border border-[#E0443E]" />
                            <div className="w-3 h-3 rounded-full bg-[#FFBD2E] border border-[#DEA123]" />
                            <div className="w-3 h-3 rounded-full bg-[#27C93F] border border-[#1AAB29]" />
                          </div>
                          {children}
                        </div>
                      );
                    },
                    p({ children }) {
                      return <p className="mb-2">{children}</p>;
                    },
                    blockquote({ children }) {
                      return (
                        <blockquote className="[&_p]:mb-0 border-l-4 pl-4 mb-4 py-1">
                          {children}
                        </blockquote>
                      );
                    },
                  }}
                >
                  {article.content}
                </ReactMarkdown>
              </div>
            </div>

            {/* 评论区 */}
            <Comment comments={comments} article={article} />
          </div>

          {/* 右侧导航区 */}
          <div className="w-full lg:w-80 flex-shrink-0">
            <div className="sticky top-20 space-y-6">
              {/* 目录 */}
              {toc.length > 0 && (
                <div className="bg-white rounded-lg p-4 shadow-sm max-h-[calc(100vh-100px)] overflow-y-auto">
                  <h3 className="text-lg mb-4 font-semibold text-gray-800">目录</h3>
                  <div className="space-y-1">
                    {toc.map((item) => (
                      <div
                        key={item.id}
                        className={`cursor-pointer hover:text-blue-600 truncate py-2 px-3 rounded-md ${activeTocId === item.id
                          ? "text-blue-600 font-medium bg-blue-50 border-l-4 border-blue-500"
                          : "text-gray-600 hover:bg-gray-50"
                          }`}
                        style={{
                          paddingLeft: `${(item.level - 1) * 1.5 + 0.75}rem`,
                          fontSize: item.level === 1 ? '1rem' : item.level === 2 ? '0.95rem' : '0.9rem'
                        }}
                        onClick={() => handleTocClick(item.id)}
                      >
                        {item.text}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 相关文章 */}
              <div className="bg-white rounded-lg p-4">
                <h3 className="text-lg font-medium mb-4">相关文章</h3>
                <div className="space-y-4">
                  {relatedArticles.map((related) => (
                    <div
                      key={related.id}
                      className="cursor-pointer hover:bg-gray-100 p-2 rounded transition-colors"
                      onClick={() => navigate(`/article/${related.id}`)}
                    >
                      <h4 className="font-medium line-clamp-2">
                        {related.title}
                      </h4>
                      <div className="flex items-center gap-2 mt-2 text-sm text-gray-500">
                        <span>{related.author.username}</span>
                        <span>·</span>
                        <span>
                          {new Date(related.publishTime).toLocaleDateString()}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>

  );
});

CurrentArticle.displayName = "CurrentArticle";
export default CurrentArticle;
